import * as cc from "cc";

const { ccclass, menu, property } = cc._decorator;
@ccclass
@menu("扩展组件/ComSortNode")
/**这个节点下所有子节点根据Y轴计算显示层级zIndex */
export default class ComSortNode extends cc.Component {

    @property({tooltip:"每次排序间隔时间/秒"})
    sortInterval : number = 0.5;

    onLoad() {
    }

    start(){
        this.schedule(this.tick.bind(this), this.sortInterval, cc.macro.REPEAT_FOREVER);
    }

    tick(dt){
        this._sortNode();

    }
    // update(dt) {
    // }

    /**排序角色层级 */
    private _sortNode() {
        this.node.children.sort((role1: cc.Node, role2: cc.Node) => {
            if (!role1 || !role2) {
                return 0;
            }
            if (!role1.isValid || !role2.isValid) {
                return 0;
            }
            if (role1.position.y > role2.position.y) {
                return -1;
            } else if (role1.position.y < role2.position.y) {
                return 1;
            } else {
                return 0;
            }
        });
    }

}